export default {
  state: {
    cartList: [],
  },
  mutations: {
    //state:模块的状态,payload:添加商品信息
    JOIN_CART(state, payload) {
      //判断购物车是否有商品信息，若有购买数量+1，若无添加该条商品信息(根据id判断)
      if (payload.flag) {
        const info = state.cartList.find((v) => v.id === payload.id)
        if (--info.buyNumber < 1) {
          state.cartList = state.cartList.filter((v) => v.id !== payload.id)
        }
      } else {
        const info = state.cartList.find((v) => v.id === payload.id)
        if (info) {
          info.buyNumber++
        } else {
          state.cartList = [
            {
              id: payload.id,
              goodsName: payload.goodsName,
              goodsPrice: payload.goodsPrice,
              buyNumber: 1,
            },
            ...state.cartList,
          ]
        }
      }
    },
  },
  getters: {
    sumPrice(state) {
      return state.cartList.reduce((sum, item) => {
        return sum + item.goodsPrice * item.buyNumber
      }, 0)
    },
  },
}
